<template>
  <div class="customer-service">
    <el-page-header @back="goBack" title="客户服务">
      <template #content>
        <span class="page-header-content">{{ customerInfo.name }}</span>
      </template>
    </el-page-header>

    <div class="service-content">
      <!-- 客户基本信息卡片 -->
      <el-card class="info-card">
        <template #header>
          <div class="card-header">
            <h3>客户信息</h3>
          </div>
        </template>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="客户姓名">{{ customerInfo.name }}</el-descriptions-item>
          <el-descriptions-item label="客户类型">
            {{ customerInfo.type === 'personal' ? '个人' : '企业' }}
          </el-descriptions-item>
          <el-descriptions-item label="手机号码">{{ customerInfo.phone }}</el-descriptions-item>
          <el-descriptions-item label="信用等级">
            <el-tag :type="getCreditRatingType(customerInfo.creditRating)">
              {{ getCreditRatingText(customerInfo.creditRating) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="贷款次数">{{ customerInfo.loanCount }}</el-descriptions-item>
          <el-descriptions-item label="累计贷款金额">
            {{ formatMoney(customerInfo.totalLoanAmount) }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 服务记录列表 -->
      <el-card class="list-card">
        <template #header>
          <div class="card-header">
            <h3>服务记录</h3>
            <el-button type="primary" @click="handleAdd">新增服务</el-button>
          </div>
        </template>

        <el-table :data="tableData" style="width: 100%" v-loading="loading">
          <el-table-column prop="type" label="服务类型" width="120">
            <template #default="scope">
              {{ getServiceTypeText(scope.row.type) }}
            </template>
          </el-table-column>
          <el-table-column prop="title" label="服务主题" width="200" />
          <el-table-column prop="content" label="服务内容" show-overflow-tooltip />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getServiceStatusType(scope.row.status)">
                {{ getServiceStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="priority" label="优先级" width="100">
            <template #default="scope">
              <el-tag :type="getPriorityType(scope.row.priority)">
                {{ getPriorityText(scope.row.priority) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column prop="handler" label="处理人" width="120" />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button 
                type="primary" 
                size="small" 
                @click="handleEdit(scope.row)"
                v-if="scope.row.status === 'pending'"
              >
                处理
              </el-button>
              <el-button 
                type="info" 
                size="small" 
                @click="handleView(scope.row)"
                v-else
              >
                查看
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                @click="handleDelete(scope.row)"
                v-if="scope.row.status === 'pending'"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 服务记录对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogType === 'add' ? '新增服务记录' : dialogType === 'edit' ? '处理服务' : '服务详情'"
      width="600px"
    >
      <el-form 
        :model="form" 
        :rules="rules" 
        ref="formRef"
        label-width="100px"
      >
        <el-form-item label="服务类型" prop="type">
          <el-select 
            v-model="form.type" 
            placeholder="请选择服务类型" 
            style="width: 100%"
            :disabled="dialogType === 'view'"
          >
            <el-option label="咨询" value="consult" />
            <el-option label="投诉" value="complaint" />
            <el-option label="建议" value="suggestion" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="服务主题" prop="title">
          <el-input 
            v-model="form.title" 
            placeholder="请输入服务主题"
            :disabled="dialogType === 'view'"
          />
        </el-form-item>
        <el-form-item label="服务内容" prop="content">
          <el-input
            type="textarea"
            v-model="form.content"
            :rows="3"
            placeholder="请输入服务内容"
            :disabled="dialogType === 'view'"
          />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select 
            v-model="form.priority" 
            placeholder="请选择优先级" 
            style="width: 100%"
            :disabled="dialogType === 'view'"
          >
            <el-option label="高" value="high" />
            <el-option label="中" value="medium" />
            <el-option label="低" value="low" />
          </el-select>
        </el-form-item>
        <template v-if="dialogType === 'edit' || dialogType === 'view'">
          <el-form-item label="处理状态" prop="status">
            <el-select 
              v-model="form.status" 
              placeholder="请选择处理状态" 
              style="width: 100%"
              :disabled="dialogType === 'view'"
            >
              <el-option label="待处理" value="pending" />
              <el-option label="处理中" value="processing" />
              <el-option label="已完成" value="completed" />
            </el-select>
          </el-form-item>
          <el-form-item label="处理记录" prop="handleNote">
            <el-input
              type="textarea"
              v-model="form.handleNote"
              :rows="3"
              placeholder="请输入处理记录"
              :disabled="dialogType === 'view'"
            />
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" v-if="dialogType !== 'view'">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'CustomerService',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const customerId = route.params.id

    // 客户信息
    const customerInfo = reactive({
      name: '张三',
      type: 'personal',
      phone: '13800138000',
      creditRating: 'A',
      loanCount: 3,
      totalLoanAmount: 500000
    })

    // 列表相关
    const loading = ref(false)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(100)

    // 表格数据
    const tableData = ref([
      {
        id: 1,
        type: 'consult',
        title: '贷款咨询',
        content: '咨询个人住房贷款相关事宜',
        status: 'completed',
        priority: 'medium',
        createTime: '2024-03-01 10:00:00',
        handler: '李四',
        handleNote: '已解答客户关于房贷的各项问题'
      }
    ])

    // 对话框相关
    const dialogVisible = ref(false)
    const dialogType = ref('add') // add, edit, view
    const formRef = ref(null)
    const form = reactive({
      type: '',
      title: '',
      content: '',
      priority: 'medium',
      status: 'pending',
      handleNote: ''
    })

    const rules = {
      type: [
        { required: true, message: '请选择服务类型', trigger: 'change' }
      ],
      title: [
        { required: true, message: '请输入服务主题', trigger: 'blur' }
      ],
      content: [
        { required: true, message: '请输入服务内容', trigger: 'blur' },
        { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
      ],
      priority: [
        { required: true, message: '请选择优先级', trigger: 'change' }
      ],
      status: [
        { required: true, message: '请选择处理状态', trigger: 'change' }
      ],
      handleNote: [
        { required: true, message: '请输入处理记录', trigger: 'blur' },
        { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
      ]
    }

    // 方法定义
    const goBack = () => {
      router.back()
    }

    const handleSearch = () => {
      loading.value = true
      // TODO: 实现查询逻辑
      setTimeout(() => {
        loading.value = false
      }, 1000)
    }

    const handleAdd = () => {
      dialogType.value = 'add'
      Object.keys(form).forEach(key => {
        form[key] = ''
      })
      form.priority = 'medium'
      form.status = 'pending'
      dialogVisible.value = true
    }

    const handleEdit = (row) => {
      dialogType.value = 'edit'
      Object.keys(form).forEach(key => {
        form[key] = row[key]
      })
      dialogVisible.value = true
    }

    const handleView = (row) => {
      dialogType.value = 'view'
      Object.keys(form).forEach(key => {
        form[key] = row[key]
      })
      dialogVisible.value = true
    }

    const handleDelete = (row) => {
      ElMessageBox.confirm(
        '确认删除该服务记录吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        // TODO: 实现删除逻辑
        ElMessage.success('删除成功')
        handleSearch()
      })
    }

    const handleSubmit = async () => {
      if (!formRef.value) return
      
      try {
        await formRef.value.validate()
        // TODO: 实现提交逻辑
        ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
        dialogVisible.value = false
        handleSearch()
      } catch (error) {
        console.error('表单验证失败:', error)
      }
    }

    const handleSizeChange = (val) => {
      pageSize.value = val
      handleSearch()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      handleSearch()
    }

    const formatMoney = (value) => {
      return `¥ ${value.toFixed(2)}`
    }

    const getCreditRatingType = (rating) => {
      const map = {
        'A': 'success',
        'B': 'warning',
        'C': 'info',
        'D': 'danger'
      }
      return map[rating]
    }

    const getCreditRatingText = (rating) => {
      const map = {
        'A': '优秀',
        'B': '良好',
        'C': '一般',
        'D': '较差'
      }
      return map[rating]
    }

    const getServiceTypeText = (type) => {
      const map = {
        'consult': '咨询',
        'complaint': '投诉',
        'suggestion': '建议',
        'other': '其他'
      }
      return map[type]
    }

    const getServiceStatusType = (status) => {
      const map = {
        'pending': 'warning',
        'processing': 'primary',
        'completed': 'success'
      }
      return map[status]
    }

    const getServiceStatusText = (status) => {
      const map = {
        'pending': '待处理',
        'processing': '处理中',
        'completed': '已完成'
      }
      return map[status]
    }

    const getPriorityType = (priority) => {
      const map = {
        'high': 'danger',
        'medium': 'warning',
        'low': 'info'
      }
      return map[priority]
    }

    const getPriorityText = (priority) => {
      const map = {
        'high': '高',
        'medium': '中',
        'low': '低'
      }
      return map[priority]
    }

    onMounted(() => {
      if (customerId) {
        // TODO: 获取客户信息和服务记录列表
        handleSearch()
      }
    })

    return {
      customerInfo,
      loading,
      currentPage,
      pageSize,
      total,
      tableData,
      dialogVisible,
      dialogType,
      formRef,
      form,
      rules,
      goBack,
      handleAdd,
      handleEdit,
      handleView,
      handleDelete,
      handleSubmit,
      handleSizeChange,
      handleCurrentChange,
      formatMoney,
      getCreditRatingType,
      getCreditRatingText,
      getServiceTypeText,
      getServiceStatusType,
      getServiceStatusText,
      getPriorityType,
      getPriorityText
    }
  }
}
</script>

<style scoped>
.customer-service {
  padding: 20px;
}

.page-header-content {
  font-size: 20px;
  font-weight: bold;
}

.service-content {
  margin-top: 20px;
}

.info-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #409EFF;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-descriptions__label) {
  font-weight: bold;
}

:deep(.el-card__body) {
  padding: 20px;
}
</style> 